#include "FontMetricsTool.h"

FontMetricsTool::~FontMetricsTool() {
    // 析构函数不需要特殊处理，因为我们在getFontMetrics中即时清理
}

// 获取字符的边界框（宽度和高度）
bool FontMetricsTool::getGlyphDimensions(FT_Face face, char ch, unsigned int fontSize, int &width, int &height) {
    // 设置字体大小
    FT_Error error = FT_Set_Pixel_Sizes(face, 0, fontSize);
    if (error) {
        cerr << "FT_Set_Pixel_Sizes failed: " << error << endl;
        return false;
    }

    // 获取字符的字形索引
    FT_UInt glyph_index = FT_Get_Char_Index(face, static_cast<FT_ULong>(ch));
    if (glyph_index == 0) {
        cerr << "Character not found in font." << endl;
        return false;
    }

    // 加载字形（不渲染）
    error = FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
    if (error) {
        cerr << "FT_Load_Glyph failed: " << error << endl;
        return false;
    }

    // 获取字形对象
    FT_Glyph glyph;
    error = FT_Get_Glyph(face->glyph, &glyph);
    if (error) {
        cerr << "FT_Get_Glyph failed: " << error << endl;
        return false;
    }

    // 获取边界框（像素单位）
    FT_BBox bbox;
    FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_PIXELS, &bbox);

    // 计算宽度和高度
    width = bbox.xMax - bbox.xMin;
    height = bbox.yMax - bbox.yMin;

    // 清理字形
    FT_Done_Glyph(glyph);
    return true;
}

// 二分查找最大字体大小
int FontMetricsTool::findMaxFontSize( char character, int screenWidth, int screenHeight) {
    int low = 1;
    int high = min(screenWidth, screenHeight) ; // 最大字体大小估计
    int maxValidSize = 0;

    while (low <= high) {
        int mid = (low + high) / 2;
        int width, height;

        if (!getGlyphDimensions(face, character, mid, width, height)) {
            high = mid - 1; // 出错时尝试更小尺寸
            continue;
        }

        if (width <= screenWidth && height <= screenHeight) {
            maxValidSize = mid; // 当前尺寸有效
            low = mid + 1; // 尝试更大的尺寸
        } else {
            high = mid - 1; // 当前尺寸过大
        }
    }

    return maxValidSize;
}

std::pair<int, int> FontMetricsTool::getFontMetrics(int fontSize) {
    // 设置字体大小
    if (FT_Set_Pixel_Sizes(face, 0, fontSize)) {
        throw std::runtime_error("无法设置字体大小");
    }
    
    // 获取字体度量信息
    int width = face->size->metrics.max_advance >> 6;  // 转换为像素
    int ascender = face->size->metrics.ascender >> 6;
    int descender = face->size->metrics.descender >> 6;
    int lineHeight = ascender - descender;
    return {width, lineHeight};
}